<template>
	<view class="content">
		<!-- <z-paging ref="paging" v-model="MessageList" @query="queryList" :auto-hide-loading-after-first-loaded="false"> -->
		<!-- <z-paging ref="paging" use-virtual-list cell-height-mode="dynamic" use-cache cache-key="MessageList"
			@query="queryList" auto-show-back-to-top :back-to-top-style="{ 'opacity':0.6 }"> -->
		<z-paging ref="paging" v-model="MessageList" :auto="false" loading-more-no-more-text="没有更多了" use-virtual-list
			auto-show-back-to-top updatePageScrollTopHeight @query="queryList" preload-page="20"
			auto-show-system-loading @innerCellClick="innerCellClick" :back-to-top-style="{ 'opacity':0.6 }">
			<template #top>
				<u-navbar class="navbar" :fixed="false" title="消息" :autoBack="navLeftIcon"
					:leftIcon="navLeftIcon ? 'arrow-left' : ''" :safeAreaInsetTop="true" style="width: 100%;"
					leftIconColor="#fff">
					<view slot="right">
						<u-icon name="/static/assets/image/img/setIcon.png" color="#fff" size="26"
							@click="openMsgSetting"></u-icon>
					</view>
				</u-navbar>


				<z-tabs ref="tabs" unit="px" scroll-count="3" :badgeMaxCount="999" active-color="#51d0d0"
					:list="tabList" :current="currentIndex" @change="tabsChange">

					<template #right>
						<view class="x-ec">
							<m-dropdown-menu class="drag" ref="filterMenu" marginTop="10" zIndex="9999">
								<template #default="{element}">
									<view class="x-c" style="width: 50px;border-left: 1px solid #e8e8e8;">
										<uni-icons fontFamily="CustomFontPlatform" color="#818181"
											:size="20">{{$utils.toUniCode('&#xe6cb;')}}</uni-icons>
									</view>
								</template>

								<template #Card>
									<view style="min-height: 200px;background-color: #fff;">
										<m-date-time pickerType="module" :InitData="DropDowmMenu_Date"
											@DateSubmit="DateSubmit($event)">
										</m-date-time>

									</view>
								</template>
							</m-dropdown-menu>

						</view>
					</template>
				</z-tabs>

			</template>

			<template #loading>
				<view style="padding: 20rpx;">
					<m-skeleton v-for="i in 5" :key="i" style="margin-bottom: 20rpx;"></m-skeleton>
				</view>
			</template>


			<template #cell="{item,index}">
				<view class="card-box">
					<!-- 顶部区域 -->
					<view class="card-header">
						<view class="header-left">
							<view class="module-name animate">{{item.ModuleName}}</view>
						</view>
						<view class="header-right">
							<u-tag :text="UnreadTextBack(item)" :type="UnreadTextBack(item)=='未读'?'error':'success'"
								plain plainFill size="mini" class="status-tag" />
						</view>
					</view>

					<!-- 内容区域 -->
					<view class="content-section">
						<view class="message-content animate">{{item.MSGContent}}</view>
						<view class="message-subject animate">{{item.MSGSubject}}</view>
					</view>

					<!-- 底部信息 -->
					<view class="card-footer">
						<view class="send-date">{{item.SendDate | timeFormat}}</view>
						<view class="sender">发起人：{{item.Sender}}</view>
					</view>
				</view>
			</template>
		</z-paging>


		<!-- 消息设置 -->
		<uni-popup ref="settingPopup" background-color="#fff" borderRadius="20px 20px 20px 20px">
			<view class="f-dc" style="height: 300px;width: 80vw;overflow: hidden;border-radius: 20px;">

				<u-navbar :fixed="false" title="消息设置" leftIcon=" " :safeAreaInsetTop="false" style="width: 100%;">
					<view slot="right">
						<u-icon name="close" color="#fff" size="20" @click="closeMsgSetting"></u-icon>
					</view>
				</u-navbar>

				<view class="flex-auto" style="padding: 10px;">
					<uni-row class="CommonBox" :gutter="20">

						<uni-col :span="8" :xm="{span: 12}" :xs="{span: 8}" :sm="{span: 4}" :lg="{span: 3}">
							<view class="CommonCard">
								<switch :checked="BtnType" @change="changeType" color="#51d0d0"
									style="transform:scale(0.7)"></switch>
								<view style="text-align: center;margin-top: 10px;font-size: 12px;">
									<text>点击{{BtnType?'关闭':'开启'}}消息图标</text>
								</view>
							</view>
						</uni-col>

						<uni-col :span="8" :xm="{span: 12}" :xs="{span: 8}" :sm="{span: 4}" :lg="{span: 3}">
							<view class="CommonCard" hover-class="cardHover" :hover-stay-time="50"
								@click="OpenManage(1)">
								<u-icon :name="MsgTypeBackFun" size="32"></u-icon>
								<view style="text-align: center;margin-top: 10px;font-size: 12px;">
									<text>消息通知权限设置</text>
								</view>
							</view>
						</uni-col>

						<uni-col :span="8" :xm="{span: 12}" :xs="{span: 8}" :sm="{span: 4}" :lg="{span: 3}">
							<view class="CommonCard" hover-class="cardHover" :hover-stay-time="50"
								@click="batchMarkAsRead">
								<u-icon name="/static/assets/image/img/batchMarkAsReadIcon.png" size="32"></u-icon>
								<view style="text-align: center;margin-top: 10px;font-size: 12px;">
									<text>一键全部已读</text>
								</view>
							</view>
						</uni-col>
					</uni-row>
				</view>

			</view>
		</uni-popup>

	</view>
</template>

<script>
	// var jpushModule = uni.requireNativePlugin("JG-JPush");
	// 每次进入，存储一遍进入的时间，下次获取数据时，该时间后的为未读消息。
	import UseSqliteFunByMsg from '@/pages/Message/common/sqlite-msg.js';
	export default {
		data() {
			return {
				sessionStartTime: 0, // 本次会话开始时间
				navLeftIcon: false,
				MessageList: [], // 消息列表 
				msgSettingType: true,
				UnreadIDs: [], // 未读ID数据
				tabList: [{
						name: '未读',
						badge: {
							count: 0
						},
					},
					{
						name: '全部',
						badge: {
							count: 0
						},
					},
				],
				currentIndex: 0,

				// 时间筛选参数
				DropDowmMenu_Date: {
					DateTitle: "",
					SDate: "",
					EDate: "",
				},
			}
		},
		onLoad(option) {
			let that = this;
			if (option.nav) {
				this.navLeftIcon = true;
			}

			// #ifdef APP-PLUS
			// 清理软件角标
			this.setBadge();

			this.getDeviceType();

			// #endif

		},
		created() {
			let that = this;

			this.queryList();
		},
		onShow() {
			this.$store.commit('ChangeAndSetStateData', {
				Name1: 'systemConfig.msgConfig.msgBtnIsHide',
				data: true
			});
			// #ifdef APP-PLUS
			// 清理软件角标
			this.setBadge();

			this.getDeviceType();

			// #endif
		},
		onHide() {
			// this.$store.commit('ChangeAndSetStateData', {
			// 	Name1: 'systemConfig.msgConfig.msgBtnIsHide',
			// 	data: false
			// });
		},
		computed: {
			BtnType() { // 是否打开消息按钮
				return this.$store.state.systemConfig.msgConfig.openMsgBtnType
			},
			tableKeyName() {
				return 'msg_' + this.$store.getters.UserInfo.Business + '_' + this.$store.getters.UserInfo.UserID
			},
			MsgTypeBackFun() {
				let icon = this.msgSettingType ? 'open' : 'close';

				return '/static/assets/image/img/' + icon + '.png'
			},
		},
		filters: {
			timeFormat(val) {
				return uni.$m.utils.dateFormat(val, 'Y-MM-dd hh:mm:ss');
			}
		},
		mounted() {
			let that = this;

			// 点击底栏消息，刷新页面
			uni.$on('msgReload', function(data) {
				console.log(data)
				if (data.status == 'reload') {
					// that.$nextTick(() => {
					that.refresh();
					// })
				}
			})
		},
		onUnload() { // 监听页面卸载, 
			uni.$off('msgReload');
			this.$store.commit('ChangeAndSetStateData', {
				Name1: 'systemConfig.msgConfig.msgBtnIsHide',
				data: !this.$store.state.systemConfig.msgConfig.openMsgBtnType
			});
			// let newlastData = this.$utils.dateFormat(new Date(), "Y-MM-dd hh:mm:ss"); // 记录最新时间
			// console.log(newlastData);
			// let sql =
			// 	`lastData='${newlastData}'`
			// UseSqliteFunByMsg.updateSqlRow(this.tableKeyName, sql)
		},
		methods: {
			// 时间筛选--时间选择
			DateSubmit(data) { // 选中时间
				this.DropDowmMenu_Date = this.$utils.deepClone(data);
				this.$refs.filterMenu.close();
				this.$refs.paging.reload();
			},

			getMSGIDByOnUpload() { // 卸载页面时获取一遍未读id
				let that = this;
				that.$store.dispatch('GetMessageInfo', {
					FEDate: '',
					Sender: '',
					ModuleName: '',
					FBDate: '',
				}).then(ret => {
					if (ret.status == 200) {

					}
				})
			},

			tabsChange(index) {
				this.currentIndex = index;
				// 将滚动条跳转到顶部
				this.$refs.paging.scrollToTop(false);
				this.$refs.paging.reload();
			},
			getDeviceType() {
				// #ifdef APP-PLUS

				const appAuthorizeSetting = uni.getAppAuthorizeSetting();

				this.msgSettingType = appAuthorizeSetting.notificationAuthorized == 'authorized' ? true : false;

				// #endif

			},
			OpenManage(type) {
				console.log(type);
				switch (type) {
					case 1: // 通知 
						uni.openAppAuthorizeSetting({
							success(res) {
								console.log(res)
							}
						});
						break;
					default:
						break;
				}
			},
			setBadge() { // 设置app角标  

				if (uni.getSystemInfoSync().platform == 'ios') {
					//导入ios UIApplication
					var UIApplication = plus.ios.import('UIApplication');
					var app = UIApplication.sharedApplication();
					//获取应用图标的数量
					var oldNum = app.applicationIconBadgeNumber();
					console.log(oldNum);

					//设置应用图标的数量
					plus.runtime.setBadgeNumber(0);
				} else {
					plus.runtime.setBadgeNumber(0);
					// jpushModule.setBadge(0);
				}
				// 通知服务端app清除了角标  
				// jpushModule.setBadge(0);
			},
			innerCellClick(item, index) {
				this.ToInfoByMsgType(item, index);
			},
			ToInfoByMsgType(data, index) {
				console.log(data, index);
				if (data.Url) {

					// 统一解析URL查询参数的方法 (复用逻辑)
					function parseQueryString(query) {
						const params = {};
						if (!query) return params;

						// 处理完整的URL或纯查询字符串
						const queryPart = query.includes('?') ?
							query.split('?')[1] || '' :
							query;

						queryPart.split('&').forEach(pair => {
							const [key, value] = pair.split('=');
							if (key) {
								params[decodeURIComponent(key)] = decodeURIComponent(value || '');
							}
						});
						return params;
					}

					const url = data.Url || '';
					console.log(url);

					// 判断是否为报表跳转

					if (url.includes('/ReportList/Table')) {
						const params = parseQueryString(url);

						this.$store.commit('ChangeAndSetStateData', {
							Name1: 'Menu',
							data: {
								APFunName: params.moduleName,
								Para: params.moduleName
							}
						});

						uni.navigateTo({
							url: "/commonPage/Report/index"
						});

					} else if (url.includes('/st_device') || url.includes('/st_mold')) {
						uni.navigateTo({
							url: url
						});
					} else {
						// 表单跳转分支
						const params = parseQueryString(url);

						// 构造表单参数对象
						const returnData = {
							detailTitle: params.objName,
							detailName: params.objName,
							keyName: params.keyName,
							keyValue: params.keyValue,
							dataInfo: {
								titleColName: '',
								showColumnsInfo: [],
								tagColumnsInfo: [],
							}
						};

						this.$store.commit('ChangeAndSetStateData', {
							Name1: 'MenuDetail',
							data: returnData
						});

						// 处理表单类对象的权限配置
						if (params.objName && params.objName.endsWith("表单")) {
							this.$store.commit('GetUnPermissionConfigInfo', {
								moduleName: params.objName.slice(0, -2) // 移除"表单"后缀
							});
						}

						uni.navigateTo({
							url: '/commonPage/Form/Edit'
						});
					}




					let UnreadIDs = JSON.parse(JSON.stringify(this.UnreadIDs));
					let MessageList = JSON.parse(JSON.stringify(this.MessageList));


					// 处理未读消息标识
					let findID = UnreadIDs.indexOf(data.MSGID)
					if (findID != -1) {
						// 从未读ID数组中移除当前消息ID

						UnreadIDs.splice(findID, 1);
						this.UnreadIDs = JSON.parse(JSON.stringify(UnreadIDs));
						if (this.currentIndex === 0) {
							MessageList.splice(findID, 1);
							this.MessageList = JSON.parse(JSON.stringify(MessageList));
							this.$refs.paging.didDeleteVirtualListCell(index);
						}
						// 更新徽标数
						this.$set(this.tabList[0].badge, 'count', this.UnreadIDs.length);

						this.$store.commit('ChangeAndSetStateData', {
							Name1: 'systemConfig.msgConfig.msgNum',
							data: this.UnreadIDs.length
						});
						// 更新本地SQLite存储
						let sql =
							`content = '${JSON.stringify(this.UnreadIDs)}'`
						UseSqliteFunByMsg.updateSqlRow(this.tableKeyName, sql);
						this.$store.commit('ChangeAndSetStateData', {
							Name1: 'systemConfig.msgConfig.hasMsg',
							data: this.UnreadIDs.length != 0
						});
					}


				}

			},
			changeType(data) {
				// this.BtnType = data.detail.value;
				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'systemConfig.msgConfig.openMsgBtnType',
					data: data.detail.value,
					StorageName: 'openMsgBtnType',
					StorageData: data.detail.value,
				});
			},
			closeMsgSetting() { // 关闭消息设置弹层
				this.$refs.settingPopup.close();

			},
			openMsgSetting() { // 打开消息设置弹层
				this.getDeviceType();

				this.$refs.settingPopup.open();
			},


			refresh() { // 搜索
				this.$refs.paging.reload()
			},
			UnreadTextBack(row) { // 未读消息映射
				if (this.UnreadIDs.length) {
					let findData = this.UnreadIDs.some(item => item == row.MSGID);

					return findData ? '未读' : '已读';
				} else {
					return "已读"
				}
			},
			queryList() {
				let that = this;
				try {
					that.$utils.showLoading("加载数据中");
					that.$store.dispatch('GetMessageInfo', {
						FEDate: that.DropDowmMenu_Date.EDate,
						Sender: '',
						ModuleName: '',
						FBDate: that.DropDowmMenu_Date.SDate,
					}).then(ret => {
						if (ret.status == 200) {
							// 初始化消息数据库
							UseSqliteFunByMsg.initSQLite(this.tableKeyName, (sqlRow => {
								// 工具函数：环境检测
								const ENV = {
									isBrowser: () => typeof window !== 'undefined',
									isWeapp: () => process.env.VUE_APP_PLATFORM === 'mp-weixin',
									isApp: () => process.env.VUE_APP_PLATFORM === 'app-plus'
								};

								// 工具函数：安全延迟执行
								const safeDelay = (callback, delay = 0) => {
									if (ENV.isWeapp()) {
										callback(); // 小程序直接执行
									} else if (ENV.isBrowser() && typeof requestIdleCallback ===
										'function') {
										requestIdleCallback(callback);
									} else {
										setTimeout(callback, delay);
									}
								};

								// 工具函数：防抖节流（可选）
								const debounce = (func, delay = 300) => {
									let timer = null;
									return (...args) => {
										clearTimeout(timer);
										timer = setTimeout(() => func.apply(this, args),
											delay);
									};
								};

								// 主逻辑开始
								let UnreadIDs = [];
								const {
									data
								} = ret;
								const ds = data.ds || [];
								const ds1 = data.ds1 || [];
								const sqlRecord = sqlRow[0] || {};

								// 1. 预处理优化（关键性能点）
								// 预计算时间戳（减少Date对象创建）
								const lastUpdateTime = new Date(sqlRecord.lastData || 0).getTime();
								// const newSelectTime = new Date(ds1[0]?.selectTime || Date.now())
								// 	.getTime();

								// 构建快速查找结构（时间复杂度O(1)）
								const currentMsgIdMap = new Map(ds.map(item => [item.MSGID, true]));

								// 2. 核心逻辑优化
								const hasContent = !!sqlRecord.content;
								if (!hasContent) {
									// 方案A：纯时间过滤（最快路径）
									UnreadIDs = ds.reduce((acc, item) => {
										const sendTime = new Date(item.SendDate).getTime();
										return sendTime > lastUpdateTime ? [...acc, item
											.MSGID
										] : acc;
									}, []);
								} else {
									// 方案B：时间+历史过滤（分阶段处理）
									const timeThreshold = lastUpdateTime;
									const historyIDs = new Set(JSON.parse(sqlRecord.content));

									// 阶段1：时间过滤（O(n)）
									const timeFiltered = [];
									for (let i = 0; i < ds.length; i++) {
										const item = ds[i];
										if (new Date(item.SendDate).getTime() > timeThreshold) {
											timeFiltered.push(item.MSGID);
										}
									}

									// 阶段2：历史ID验证（O(m)）
									const validHistory = [];
									for (const id of historyIDs) {
										if (currentMsgIdMap.has(id)) validHistory.push(id);
									}

									// 阶段3：合并去重（O(n+m)）
									const merged = new Set([...timeFiltered, ...validHistory]);
									UnreadIDs = Array.from(merged);
								}

								// 3. 视图更新优化
								that.$set(that.tabList[0].badge, 'count', UnreadIDs.length);
								that.UnreadIDs = Object.freeze([...UnreadIDs]); // 冻结数组

								// 4. 分页逻辑优化（使用引用传递）
								const targetData = (that.currentIndex === 0) ? ds.filter(item =>
									UnreadIDs.includes(item.MSGID)) : ds;

								// 使用虚拟列表优化渲染（需配合组件实现）
								if (that.$refs.paging?.setLocalPaging) {
									that.$refs.paging.setLocalPaging(targetData);
								}

								// 5. 存储优化（兼容性延迟写入）
								const saveToDB = debounce(() => {
									if (UnreadIDs.length === 0) return;

									const content = JSON.stringify(UnreadIDs);
									let newlastData = that.$utils.dateFormat(new Date(ret.data
										.ds1[0].selectTime), "Y-MM-dd hh:mm:ss"); // 记录最新时间
									let sql =
										`content = '${content}', lastData='${newlastData}'`
									UseSqliteFunByMsg.updateSqlRow(that.tableKeyName, sql)

									that.$store.commit('ChangeAndSetStateData', {
										Name1: 'systemConfig.msgConfig.hasMsg',
										data: !that.$utils.isEmpty(content)
									});
								}, 300);

								safeDelay(saveToDB); // 安全延迟执行


								that.$refs.paging.endRefresh();
								that.$utils.hideLoading();
								that.$forceUpdate();
							}));

						} else {
							that.$refs.paging.complete([]);
							that.$refs.paging.endRefresh();
							that.$utils.hideLoading();
						}
					}).catch((err) => {
						console.log(err)
						that.$utils.hideLoading();
						that.$refs.paging.complete(false);
					})
				} catch (e) {
					that.$utils.hideLoading();
					console.log(e)
					//TODO handle the exception
				}

			},
			batchMarkAsRead() { // 一键已读
				// 记录最新时间
				let newlastData = this.$utils.dateFormat(new Date(), "Y-MM-dd hh:mm:ss");
				let sql = `content = '${null}', lastData='${newlastData}'`;
				UseSqliteFunByMsg.updateSqlRow(this.tableKeyName, sql);
				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'systemConfig.msgConfig.hasMsg',
					data: false
				});
				this.closeMsgSetting();
				this.$refs.paging.reload();
				uni.showToast({
					icon: 'success',
					title: "成功",
					duration: 1000
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	$h-padding: 15rpx;
	$v-padding: 20rpx;
	$radius: 10rpx;

	// 设置列表盒子的样式
	::v-deep.zp-list-container {
		padding: 20rpx !important;
	}

	.content {
		background-color: #f0f1f5;
		// height: 80vh;
		background-color: #f6f6f6;
		// padding: calc(50px + env(safe-area-inset-top)) $h-padding 0;
	}

	.u-cell__body {
		padding: 20rpx;
	}

	.SearchBox {
		background-color: #fff;
		background-color: #51d0d0;
		padding: 16rpx 28px;

		.MenuText {
			font-size: 14px;
			border-right: 1px solid #999;
			padding-right: 10px;
			margin-right: 4px;
		}
	}

	.CommonBox {

		.CommonCard {
			background-color: #f6f6f6;
			border-radius: 12px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 15px 0;
			margin-bottom: 10px;
			box-shadow: 1px 1px 7px -6px #bababa;
		}

		.cardHover {
			background-color: rgba(81, 208, 208, 0.5);
			color: #fff;
		}
	}

	.card-box {
		position: relative;
		border-radius: 16rpx;
		padding: 24rpx;
		background-color: #fff;
		margin: 24rpx 24rpx 0;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
		transition: all 0.3s ease;

		/* 顶部布局 */
		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			margin-bottom: 16rpx;
			padding-bottom: 16rpx;
			border-bottom: 1rpx solid #f5f5f7;

			.header-left {
				flex: 1;
				min-width: 0;
				/* 防止内容溢出 */

				.module-name {
					font-size: 16px;
					font-weight: 600;
					color: #333;
					line-height: 1.4;
					/* 单行省略 */
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					padding-right: 20rpx;
				}
			}

			.header-right {
				flex-shrink: 0;

				.status-tag {
					transform: translateY(-4rpx);
					/* 微调标签位置 */
				}
			}
		}

		/* 内容区域 */
		.content-section {

			.message-content,
			.message-subject {
				color: #535353;
				font-size: 13px;
				line-height: 1.6;
				text-align: justify;
				padding: 6px 0;
			}

			.message-content {
				position: relative;
				padding-left: 40rpx;

				&::before {
					content: "“";
					position: absolute;
					left: 0;
					top: 4rpx;
					font-size: 20px;
					color: #c0c4cc;
					line-height: 1;
				}
			}

			.message-subject {
				margin-top: 8rpx;
				padding-left: 40rpx;
				color: #666;
			}
		}

		/* 底部信息 */
		.card-footer {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 16rpx;
			padding-top: 16rpx;
			border-top: 1rpx solid #f5f5f7;
			color: #999;
			font-size: 12px;

			.send-date {
				flex: 1;
			}

			.sender {
				flex-shrink: 0;
				max-width: 60%;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				text-align: right;
			}
		}
	}

	/* 动画效果 */
	.animate {
		transition: all 0.3s;

		&:active {
			opacity: 0.8;
			transform: scale(0.98);
		}
	}
</style>